<template>
  <div class="min-h-screen bg-gray-50">
    <header class="dashboard-header">
      <div class="container">
        <div class="header-content">
          <div class="brand">
            <div class="brand-icon">
              <i class="fas fa-paper-plane text-xl"></i>
            </div>
            <div class="brand-text">
              <h1>在线 SEMRUSH 提交</h1>
              <p>提交域名或链接进行数据采集</p>
            </div>
          </div>
          <div class="header-actions">
            <router-link to="/" class="refresh-btn">
              <i class="fas fa-arrow-left mr-2"></i>返回仪表盘
            </router-link>
          </div>
        </div>
      </div>
    </header>

    <main class="dashboard-main">
      <div class="max-w-8xl mx-auto px-4 space-y-6">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
          <!-- Tabs: 单条 / 批量 -->
          <div class="flex items-center justify-center mb-3">
            <div class="inline-flex rounded-lg overflow-hidden border border-gray-200">
              <button
                class="px-4 py-2 text-sm"
                :class="searchTab === 'single' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700'"
                @click="searchTab = 'single'"
              >单条查询</button>
              <button
                class="px-4 py-2 text-sm"
                :class="searchTab === 'batch' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700'"
                @click="searchTab = 'batch'"
              >批量查询</button>
            </div>
          </div>

          <div class="flex items-center justify-center" v-if="searchTab === 'single'">
            <div class="search-container w-full max-w-4xl">
              <select class="search-type-select" v-model="submitType">
                <option value="domain">域名</option>
                <option value="url">链接</option>
              </select>
              <div class="search-input">
                <i class="fas fa-search search-icon"></i>
                <input
                  v-model="inputValue"
                  :placeholder="placeholderText"
                  @keyup.enter="handleSubmit"
                />
                <button
                  type="button"
                  class="search-btn"
                  :disabled="loading"
                  @click="handleSubmit"
                >
                  <span v-if="loading">提交中...</span>
                  <span v-else>提交</span>
                </button>
              </div>
            </div>
          </div>

          <div v-else class="w-full max-w-4xl mx-auto">
            <div class="flex items-center justify-between mb-2">
              <label class="block text-sm text-gray-600">每行一个链接或域名（最多 {{ MAX_BATCH }} 条）</label>
              <!-- 批量模式筛选按钮：域名/链接 -->
              <div class="inline-flex rounded-lg overflow-hidden border border-gray-200">
                <button
                  class="px-3 py-1 text-xs"
                  :class="submitType === 'domain' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700'"
                  @click="submitType = 'domain'"
                >域名</button>
                <button
                  class="px-3 py-1 text-xs"
                  :class="submitType === 'url' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700'"
                  @click="submitType = 'url'"
                >链接</button>
              </div>
            </div>
            <textarea
              v-model="batchText"
              class="w-full border border-gray-300 rounded-lg p-3 focus:outline-none focus:ring-2 focus:ring-blue-500 h-48"
            />
            <div class="flex items-center justify-between mt-2 text-sm text-gray-600">
              <div>
                模式: <span class="font-semibold">{{ submitType === 'domain' ? '域名' : '链接' }}</span>
                <span class="mx-2">|</span>
                有效: <span class="font-semibold">{{ batchStats.valid }}</span>
                <span class="mx-2">|</span>
                重复: <span class="font-semibold">{{ batchStats.duplicates }}</span>
                <span class="mx-2">|</span>
                无效: <span class="font-semibold">{{ batchStats.invalid }}</span>
                <span class="mx-2">|</span>
                空行: <span class="font-semibold">{{ batchStats.empty }}</span>
              </div>
              <div>
                <button class="px-3 py-1 rounded bg-gray-100 hover:bg-gray-200 mr-2" @click="batchText = ''" :disabled="batchLoading">清空</button>
                <button class="px-4 py-1 rounded bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-60" :disabled="batchDisabled" @click="handleBatchSubmit">
                  <span v-if="batchLoading">提交中...</span>
                  <span v-else>提交批量（{{ batchItems.length }}）</span>
                </button>
              </div>
            </div>
            <div v-if="batchItems.length" class="mt-3 text-sm text-gray-500">
              预览（前 5 条）：
              <ul class="list-disc pl-5 mt-1">
                <li v-for="(item, i) in batchItems.slice(0, 5)" :key="i" class="truncate">{{ item }}</li>
              </ul>
            </div>
            <div v-if="batchInvalid.length" class="mt-2 text-xs text-red-600">
              无效（前 3 条）：
              <ul class="list-disc pl-5 mt-1">
                <li v-for="(item, i) in batchInvalid.slice(0, 3)" :key="i" class="truncate">{{ item }}</li>
              </ul>
            </div>
          </div>
          <div class="text-gray-500 text-sm mt-3 text-center">
            示例：域名填入 example.com；链接填入 https://www.example.com/path
          </div>
          <div v-if="searchTab === 'single' && currentQuery.target" class="mt-3 flex items-center justify-center text-sm">
            <span class="inline-flex items-center px-3 py-1 rounded-full bg-blue-50 text-blue-700 mr-2">
              <i :class="currentQuery.mode==='url' ? 'fas fa-link mr-2' : 'fas fa-globe mr-2'"></i>
              {{ currentQuery.mode === 'url' ? '链接' : '域名' }}
            </span>
            <span class="inline-flex items-center px-3 py-1 rounded-full bg-gray-100 text-gray-700">
              <i class="fas fa-bullseye mr-2"></i>
              {{ currentQuery.target }}
            </span>
          </div>
          <div v-if="currentQuery.resolved_domain" class="text-center text-xs text-gray-400 mt-1">
            已解析域名：{{ currentQuery.resolved_domain }}
          </div>
          
        </div>

      <!-- 概览信息卡片（来自接口 summary 字段） - 批量模式不显示 -->
      <div v-if="searchTab === 'single'" class="data-table" style="padding: 1.5rem;">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div class="metric-card card-hover">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-sm text-gray-600 mb-1">AS分数</div>
                <div class="trend-value">{{ summary?.authority_score ?? '-' }}</div>
              </div>
              <div class="w-16 h-16 relative">
                <svg class="progress-ring w-16 h-16">
                  <circle class="progress-ring-circle" cx="32" cy="32" r="28"></circle>
                  <circle class="progress-ring-progress" cx="32" cy="32" r="28" style="stroke-dashoffset: 62.8;"></circle>
                </svg>
                <div class="absolute inset-0 flex items-center justify-center">
                  <i class="fas fa-bolt text-blue-600"></i>
                </div>
              </div>
            </div>
          </div>

          <div class="metric-card card-hover">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-sm text-gray-600 mb-1">反向链接数量</div>
                <div class="trend-value">{{ formatNumber(Number(summary?.backlinks || 0)) }}</div>
              </div>
              <div class="w-16 h-16 relative">
                <svg class="progress-ring w-16 h-16">
                  <circle class="progress-ring-circle" cx="32" cy="32" r="28"></circle>
                  <circle class="progress-ring-progress" cx="32" cy="32" r="28" style="stroke-dashoffset: 62.8;"></circle>
                </svg>
                <div class="absolute inset-0 flex items-center justify-center">
                  <i class="fas fa-link text-blue-600"></i>
                </div>
              </div>
            </div>
          </div>

          <div class="metric-card card-hover">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-sm text-gray-600 mb-1">引荐域名数量</div>
                <div class="trend-value">{{ formatNumber(Number(summary?.referring_domains || 0)) }}</div>
              </div>
              <div class="w-16 h-16 relative">
                <svg class="progress-ring w-16 h-16">
                  <circle class="progress-ring-circle" cx="32" cy="32" r="28"></circle>
                  <circle class="progress-ring-progress" cx="32" cy="32" r="28" style="stroke-dashoffset: 62.8;"></circle>
                </svg>
                <div class="absolute inset-0 flex items-center justify-center">
                  <i class="fas fa-globe text-blue-600"></i>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="!summary" class="text-sm text-gray-400 mt-2">提交后显示概览信息</div>
      </div>

      <!-- 单条：趋势图（带域名标题） -->
      <div v-if="searchTab === 'single' && trendData.length" class="data-table" style="padding: 1.5rem;">
        <div class="text-lg font-semibold text-gray-800 mb-2">
          {{ currentQuery.resolved_domain || currentQuery.target || '查询结果' }}
        </div>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div class="chart-card">
            <div class="chart-title">流量趋势</div>
            <div ref="trafficChartRef" class="chart-container"></div>
          </div>
          <div class="chart-card">
            <div class="chart-title">关键词趋势</div>
            <div ref="keywordChartRef" class="chart-container"></div>
          </div>
        </div>
      </div>

      <!-- 单条：关键词Top列表 -->
      <div v-if="searchTab === 'single' && topKeywords.length" class="data-table" style="padding: 1.5rem;">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          <div class="p-4 border-b border-gray-200 flex items-center justify-between">
            <h3 class="text-lg font-semibold text-gray-800">关键词 Top 列表</h3>
            <div class="text-sm text-gray-500">显示前 10 条</div>
          </div>
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-gray-50">
                <tr>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">排名</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">关键词</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">流量</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">搜索量</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">CPC</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">流量占比</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">当前排名</th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr v-for="(kw, idx) in topKeywords" :key="idx" class="hover:bg-gray-50">
                  <td class="px-6 py-3 whitespace-nowrap">
                    <span class="inline-block min-w-[28px] text-center rounded-full px-2 py-1 text-xs font-semibold"
                          :class="idx===0?'bg-red-500 text-white': idx===1?'bg-yellow-500 text-white': idx===2?'bg-blue-500 text-white':'bg-gray-200 text-gray-700'">
                      {{ idx + 1 }}
                    </span>
                  </td>
                  <td class="px-6 py-3 whitespace-nowrap">
                    <div class="text-sm font-medium text-gray-900">{{ kw.phrase || 'N/A' }}</div>
                  </td>
                  <td class="px-6 py-3 whitespace-nowrap">
                    <div class="text-sm text-gray-900">{{ formatNumber(kw.traffic || 0) }}</div>
                  </td>
                  <td class="px-6 py-3 whitespace-nowrap">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                      {{ formatSearchVolume(kw) }}
                    </span>
                  </td>
                  <td class="px-6 py-3 whitespace-nowrap">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                      {{ kw.cpc ?? 0 }}
                    </span>
                  </td>
                  <td class="px-6 py-3 whitespace-nowrap">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                      {{ kw.trafficPercent ?? 0 }}%
                    </span>
                  </td>
                  <td class="px-6 py-3 whitespace-nowrap">
                    <div class="text-sm text-gray-900">#{{ kw.position ?? '-' }}</div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      </div>
      <!-- 批量：为每个目标渲染趋势图（不显示 summary）-->
      <div v-if="searchTab === 'batch' && batchResults.length" class="max-w-8xl mx-auto px-4 space-y-6">
        <div v-for="(item, idx) in batchResults" :key="idx" class="data-table" style="padding: 1.5rem;">
          <div class="text-lg font-semibold text-gray-800 mb-2">
            {{ item?.resolved?.domain || item?.target || `目标 ${idx + 1}` }}
          </div>
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div class="chart-card">
              <div class="chart-title">流量趋势</div>
              <div :ref="setBatchTrafficRef(idx)" class="chart-container"></div>
            </div>
            <div class="chart-card">
              <div class="chart-title">关键词趋势</div>
              <div :ref="setBatchKeywordRef(idx)" class="chart-container"></div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
  
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onBeforeUnmount, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { BASE_URL } from '../main'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'

const submitType = ref<'domain' | 'url'>('domain')
const inputValue = ref('')
const loading = ref(false)
const searchTab = ref<'single' | 'batch'>('single')
// 概览信息（接口返回的 summary 字段）
const summary = ref<{ authority_score?: number | string; backlinks?: number; referring_domains?: number } | null>(null)

// 当前查询信息（用于显示搜索结果）
interface QueryInfo {
  mode?: 'domain' | 'url'
  target?: string
  resolved_domain?: string
  fetched_at?: string
}
const currentQuery = ref<QueryInfo>({})

// 批量查询
const MAX_BATCH = 200
const batchText = ref('')
const batchLoading = ref(false)
// 拆分与筛选
const batchAllUnique = computed(() => {
  const lines = batchText.value.split(/\r?\n/).map(l => l.trim())
  const nonEmpty = lines.filter(Boolean)
  return Array.from(new Set(nonEmpty)).slice(0, MAX_BATCH)
})
const batchItems = computed(() => {
  const validator = submitType.value === 'domain' ? isValidDomain : isValidUrl
  return batchAllUnique.value.filter(validator)
})
const batchInvalid = computed(() => {
  const validator = submitType.value === 'domain' ? isValidDomain : isValidUrl
  return batchAllUnique.value.filter(v => !validator(v))
})
const batchStats = computed(() => {
  const lines = batchText.value.split(/\r?\n/)
  const empty = lines.filter(l => !l.trim()).length
  const nonEmpty = lines.length - empty
  const duplicates = Math.max(nonEmpty - new Set(lines.filter(l => l.trim())).size, 0)
  const valid = batchItems.value.length
  const invalid = batchInvalid.value.length
  return { empty, duplicates, valid, invalid }
})
const batchDisabled = computed(() => batchItems.value.length === 0 || batchLoading.value)
// 批量结果结构（用于渲染）
interface BatchSeries {
  dates: string[]
  traffic: number[]
  top3: number[]
  rank_4_10: number[]
  rank_11_20: number[]
  rank_21_50: number[]
  rank_51_100: number[]
  serp: number[]
}
interface BatchResultItem {
  mode?: 'domain' | 'url'
  target?: string
  resolved?: { domain?: string }
  semrush_data?: {
    overview_trend?: { data: TrendDataItem[] }
    keyword_ranking?: { data: any[] }
  }
  summary?: any
  overview_trend?: TrendDataItem[]
  series?: Partial<BatchSeries> & { dates?: string[] }
}
const batchResults = ref<BatchResultItem[]>([])

const handleBatchSubmit = async () => {
  if (batchItems.value.length === 0) {
    ElMessage.warning('请输入需要提交的内容')
    return
  }
  batchLoading.value = true
  try {
    // 批量查询：POST /api/v1/semrush/batch（后端将返回每个目标的趋势数据）
    const payload = { mode: submitType.value, targets: batchItems.value }
    const { data } = await axios.post(`${BASE_URL}/api/v1/semrush/batch`, payload, {
      headers: {
        'Content-Type': 'application/json',
        'X-API': 'YAEW9qWA9R5dKL32wf8c',
        'x-api-key': 'YAEW9qWA9R5dKL32wf8c',
      },
      timeout: 180000,
    })
    // 兼容不同返回字段（等待你后续接口确定）
    batchResults.value = data?.items || data?.results || data?.data || []
    if (!Array.isArray(batchResults.value)) batchResults.value = []
    ElMessage.success(`批量查询完成：共 ${batchItems.value.length} 条，渲染 ${batchResults.value.length} 条`)
    await nextTick()
    initBatchCharts()
  } catch (e) {
    ElMessage.error('批量提交失败，请稍后重试')
  } finally {
    batchLoading.value = false
  }
}

// 批量图表 refs 与实例
const batchTrafficRefs = ref<Record<number, HTMLElement | null>>({})
const batchKeywordRefs = ref<Record<number, HTMLElement | null>>({})
const setBatchTrafficRef = (idx: number) => (el: HTMLElement | null) => { if (el) batchTrafficRefs.value[idx] = el }
const setBatchKeywordRef = (idx: number) => (el: HTMLElement | null) => { if (el) batchKeywordRefs.value[idx] = el }
let batchTrafficCharts: Record<number, echarts.ECharts | null> = {}
let batchKeywordCharts: Record<number, echarts.ECharts | null> = {}

const disposeBatchCharts = () => {
  Object.values(batchTrafficCharts).forEach(c => c?.dispose())
  Object.values(batchKeywordCharts).forEach(c => c?.dispose())
  batchTrafficCharts = {}
  batchKeywordCharts = {}
}

// 提取批量 item 的绘图序列：优先使用后端拆好的 series，没有则从原始趋势回退计算
const getBatchSeries = (item: BatchResultItem) => {
  const s: any = item.series || {}
  const directDates: string[] | undefined = s.dates || (item as any).dates
  const directTraffic: number[] | undefined = s.traffic || (item as any).traffic
  const trend: any[] = (item.overview_trend as any) || item?.semrush_data?.overview_trend?.data || []

  const computedDates = trend.map((d: any) => {
    const ds = d?.date || ''
    return `${ds.slice(0,4)}-${ds.slice(4,6)}-${ds.slice(6,8)}`
  })
  const computedTraffic = trend.map((i: any) => (i?.organicTraffic ?? i?.traffic ?? 0))
  const pos = (i: any, idx: number) => (i?.organicPositionsTrend?.[idx] ?? 0)
  const sumRange = (i: any, a: number, b: number) => {
    const arr: number[] = i?.organicPositionsTrend || []
    let sum = 0
    for (let k = a; k <= b && k < arr.length; k++) sum += arr[k] || 0
    return sum
  }
  const toSeries = (fn: (i: any) => number) => trend.map(fn)

  return {
    dates: directDates || computedDates,
    traffic: directTraffic || computedTraffic,
    top3: s.top3 || toSeries((i) => pos(i, 0)),
    rank_4_10: s.rank_4_10 || toSeries((i) => pos(i, 1)),
    rank_11_20: s.rank_11_20 || toSeries((i) => pos(i, 2)),
    rank_21_50: s.rank_21_50 || toSeries((i) => sumRange(i, 3, 5)),
    rank_51_100: s.rank_51_100 || toSeries((i) => sumRange(i, 6, 10)),
    serp: s.serp || toSeries((i) => i?.serpFeaturesPositions || 0),
  } as BatchSeries
}

const initBatchCharts = () => {
  disposeBatchCharts()
  batchResults.value.forEach((item, idx) => {
    const s = getBatchSeries(item)
    const dates = s.dates || []
    if (!dates.length) return
    // 流量趋势
    const tEl = batchTrafficRefs.value[idx]
    if (tEl) {
      const chart = echarts.init(tEl)
      batchTrafficCharts[idx] = chart
      chart.setOption({
        tooltip: { trigger: 'axis' },
        grid: { left: '3%', right: '4%', bottom: '3%', top: '8%', containLabel: true },
        xAxis: { type: 'category', boundaryGap: false, data: dates },
        yAxis: { type: 'value', name: '流量' },
        series: [{
          name: '自然流量', type: 'line', smooth: true,
          data: s.traffic,
          lineStyle: { width: 3, color: '#3b82f6' },
          areaStyle: { color: 'rgba(59, 130, 246, 0.10)' },
        }]
      } as EChartsOption)
    }
    // 关键词趋势
    const kEl = batchKeywordRefs.value[idx]
    if (kEl) {
      const chart = echarts.init(kEl)
      batchKeywordCharts[idx] = chart
      chart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: ['排名前3','排名4-10','排名11-20','排名21-50','排名51-100','SERP精选'], top: 'top' },
        grid: { left: '3%', right: '4%', bottom: '3%', top: '15%', containLabel: true },
        xAxis: { type: 'category', boundaryGap: false, data: dates },
        yAxis: { type: 'value', name: '关键词数量' },
        series: [
          { name: '排名前3', type: 'line', smooth: true, data: s.top3, color: '#ef4444', lineStyle: { width: 3, color: '#ef4444' } },
          { name: '排名4-10', type: 'line', smooth: true, data: s.rank_4_10, color: '#f59e0b', lineStyle: { width: 3, color: '#f59e0b' } },
          { name: '排名11-20', type: 'line', smooth: true, data: s.rank_11_20, color: '#3b82f6', lineStyle: { width: 3, color: '#3b82f6' } },
          { name: '排名21-50', type: 'line', smooth: true, data: s.rank_21_50, color: '#06b6d4', lineStyle: { width: 3, color: '#06b6d4' } },
          { name: '排名51-100', type: 'line', smooth: true, data: s.rank_51_100, color: '#93c5fd', lineStyle: { width: 3, color: '#93c5fd' } },
          { name: 'SERP精选', type: 'line', smooth: true, data: s.serp, color: '#8b5cf6', lineStyle: { width: 3, color: '#8b5cf6' } },
        ]
      } as EChartsOption)
    }
  })
}

// 接收接口返回的趋势数据
interface TrendDataItem {
  date: string
  organicTraffic?: number
  organicTrafficBranded?: number
  organicTrafficNonBranded?: number
  organicTrafficCost?: number
  traffic?: number
  trafficBranded?: number
  trafficNonBranded?: number
  trafficCost?: number
  organicPositionsTrend: number[]
  serpFeaturesPositions: number
}

const trendData = ref<TrendDataItem[]>([])
const trafficChartRef = ref<HTMLElement | null>(null)
const keywordChartRef = ref<HTMLElement | null>(null)
let trafficChart: echarts.ECharts | null = null
let keywordChart: echarts.ECharts | null = null

// 关键词排行数据与工具
type KeywordItem = any
const keywordRanking = ref<KeywordItem[]>([])
const topKeywords = computed(() => (keywordRanking.value || []).slice(0, 10))

const formatNumber = (n: number) => new Intl.NumberFormat('en-US').format(n || 0)
const formatSearchVolume = (item: any) => {
  const trends = item?.trends
  let v = 0
  if (Array.isArray(trends) && trends.length > 0) v = trends[trends.length - 1]
  else v = item?.volume || 0
  return v >= 10000 ? `${(v / 10000).toFixed(2)}K` : `${v}`
}

const placeholderText = computed(() => submitType.value === 'domain' ? '请输入域名，例如：example.com' : '请输入链接，例如：https://www.example.com/path')

const isValidDomain = (val: string) => {
  const domainRegex = /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)\.(?:[A-Za-z]{2,})(?:\.[A-Za-z]{2,})*$/
  return domainRegex.test(val)
}

const isValidUrl = (val: string) => {
  try {
    const u = new URL(val)
    return !!u.protocol && !!u.host
  } catch {
    return false
  }
}

const handleSubmit = async () => {
  const value = inputValue.value.trim()
  if (!value) {
    ElMessage.warning('请输入要提交的内容')
    return
  }
  if (submitType.value === 'domain' && !isValidDomain(value)) {
    ElMessage.warning('请输入有效的域名，例如：example.com')
    return
  }
  if (submitType.value === 'url' && !isValidUrl(value)) {
    ElMessage.warning('请输入有效的链接，例如：https://example.com')
    return
  }

  loading.value = true
  try {
    // 统一单项查询：GET /api/v1/semrush?mode=xxx&target=yyy
    const { data } = await axios.get(`${BASE_URL}/api/v1/semrush`, {
      params: {
        mode: submitType.value,
        target: value,
      },
      headers: {
        'X-API': 'YAEW9qWA9R5dKL32wf8c',
        'x-api-key': 'YAEW9qWA9R5dKL32wf8c',
      },
    })
    ElMessage.success('提交成功，已开始处理')
    inputValue.value = ''

    // 解析趋势与关键词数据用于渲染
    const list = data?.semrush_data?.overview_trend?.data || []
    trendData.value = Array.isArray(list) ? list : []
    const klist = data?.semrush_data?.keyword_ranking?.data || []
    keywordRanking.value = Array.isArray(klist) ? klist : []
    summary.value = data?.summary || data?.semrush_data?.summary || null
    currentQuery.value = {
      mode: data?.mode,
      target: data?.target,
      resolved_domain: data?.resolved?.domain,
      fetched_at: data?.fetched_at,
    }
    await nextTick()
    initCharts()
  } catch (e) {
    ElMessage.error('提交失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const initCharts = () => {
  // 销毁旧实例
  trafficChart?.dispose()
  keywordChart?.dispose()

  if (!trendData.value || trendData.value.length === 0) return

  const dates = trendData.value.map((item) => {
    const ds = item.date || ''
    return `${ds.slice(0, 4)}-${ds.slice(4, 6)}-${ds.slice(6, 8)}`
  })

  // 流量趋势（使用 organicTraffic）
  if (trafficChartRef.value) {
    trafficChart = echarts.init(trafficChartRef.value)
    const trafficOption: EChartsOption = {
      tooltip: { trigger: 'axis' },
      grid: { left: '3%', right: '4%', bottom: '3%', top: '8%', containLabel: true },
      xAxis: { type: 'category', boundaryGap: false, data: dates },
      yAxis: { type: 'value', name: '流量' },
      series: [
        {
          name: '自然流量',
          type: 'line',
          smooth: true,
          data: trendData.value.map((i) => (i.organicTraffic ?? i.traffic ?? 0)),
          lineStyle: { width: 3, color: '#3b82f6' },
          areaStyle: { color: 'rgba(59, 130, 246, 0.10)' },
        },
      ],
    }
    trafficChart.setOption(trafficOption)
  }

  // 关键词趋势（按排名区间拆分）
  if (keywordChartRef.value) {
    keywordChart = echarts.init(keywordChartRef.value)
    const series: any[] = []

    const pick = (idx: number) => trendData.value.map((i) => (i.organicPositionsTrend?.[idx] ?? 0))
    const sumRange = (start: number, end: number) =>
      trendData.value.map((i) => {
        const arr = i.organicPositionsTrend || []
        let s = 0
        for (let k = start; k <= end && k < arr.length; k++) s += arr[k] || 0
        return s
      })

    series.push({ name: '排名前3', type: 'line', smooth: true, data: pick(0), color: '#ef4444', lineStyle: { width: 3, color: '#ef4444' } })
    series.push({ name: '排名4-10', type: 'line', smooth: true, data: pick(1), color: '#f59e0b', lineStyle: { width: 3, color: '#f59e0b' } })
    series.push({ name: '排名11-20', type: 'line', smooth: true, data: pick(2), color: '#3b82f6', lineStyle: { width: 3, color: '#3b82f6' } })
    series.push({ name: '排名21-50', type: 'line', smooth: true, data: sumRange(3, 5), color: '#06b6d4', lineStyle: { width: 3, color: '#06b6d4' } })
    series.push({ name: '排名51-100', type: 'line', smooth: true, data: sumRange(6, 10), color: '#93c5fd', lineStyle: { width: 3, color: '#93c5fd' } })
    series.push({ name: 'SERP精选', type: 'line', smooth: true, data: trendData.value.map((i) => i.serpFeaturesPositions || 0), color: '#8b5cf6', lineStyle: { width: 3, color: '#8b5cf6' } })

    const keywordOption: EChartsOption = {
      tooltip: { trigger: 'axis' },
      legend: { data: ['排名前3', '排名4-10', '排名11-20', '排名21-50', '排名51-100', 'SERP精选'], top: 'top' },
      grid: { left: '3%', right: '4%', bottom: '3%', top: '15%', containLabel: true },
      xAxis: { type: 'category', boundaryGap: false, data: dates },
      yAxis: { type: 'value', name: '关键词数量' },
      series,
    }
    keywordChart.setOption(keywordOption)
  }

}

const onResize = () => {
  trafficChart?.resize()
  keywordChart?.resize()
  Object.values(batchTrafficCharts).forEach(c => c?.resize())
  Object.values(batchKeywordCharts).forEach(c => c?.resize())
}

onMounted(() => {
  if (trendData.value.length > 0) initCharts()
  window.addEventListener('resize', onResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', onResize)
  trafficChart?.dispose()
  keywordChart?.dispose()
  disposeBatchCharts()
})
</script>

<style scoped>
/* 简单图表容器样式 */
.chart-card {
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 16px;
}

.chart-title {
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 12px;
}

.chart-container {
  height: 320px;
}

/* 概览卡片样式（简化版，与 TrendDialog 保持一致风格） */
.metric-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
}

.card-hover:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.1);
}

.trend-value {
  font-size: 2rem;
  font-weight: 700;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.progress-ring {
  transform: rotate(-90deg);
}

.progress-ring-circle {
  stroke: #e5e7eb;
  stroke-width: 4;
  fill: transparent;
  stroke-linecap: round;
}

.progress-ring-progress {
  stroke: #3b82f6;
  stroke-width: 4;
  fill: transparent;
  stroke-linecap: round;
  stroke-dasharray: 251.2;
  stroke-dashoffset: 125.6;
  transition: stroke-dashoffset 1s ease;
}
</style>
